package com.wind.utils;

import java.util.*;

/**
 * <p>
 *    字符串工具类
 * </p>
 * @date    2024-12-10 16:59
 * @version v1.0
 */
public class StringUtil {

    private static final Random random = new Random();
    private static final char[] codes = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
            'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n'
            , 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
            'y', 'z'};
    private static final char[] nums = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};


    /**
     * 判断字符串是否为null或空字符串
     * @param str
     * @return
     */
    public static boolean isEmpty(String str){
        return str == null || ("".equals(str.trim()));
    }

    /**
     * 判断字符串不为空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str){
        return !isEmpty(str);
    }

    /**
     * 获取32位的UUID
     * @return
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-", "");
    }


    /**
     * 字符串分隔 StringTokenizer效率是三种分隔方法中最快的
     * @param str
     * @param sign
     * @return
     */
    public static String[] split(String str, String sign){
        if(str == null){
            return new String[]{};
        }
        StringTokenizer token = new StringTokenizer(str,sign);
        String[] strArr = new String[token.countTokens()];
        int i = 0;
        while(token.hasMoreElements()){
            strArr[i] = token.nextElement().toString();
            i++;
        }
        return strArr;
    }

    /**
     * 获取指定长度由数字和字母组成的字符串core
     * @param length 取偶数
     * @return
     */
    public static String getRandom(int length) {
        StringBuilder s = new StringBuilder();
        int n = 0;
        int m = 0;
        for (int i = 0; i < length; i++) {
            if (n == length / 2) {
                s.append(getRandomNum());
                m++;
            } else if (m == length / 2) {
                s.append(getRandomLetter());
                n++;
            } else {
                int ri = random.nextInt(2);
                if (ri == 0) {
                    m++;
                } else {
                    n++;
                }
                s.append(ri == 0 ? getRandomNum() : getRandomLetter());
            }
        }
        return s.toString();
    }

    /**
     * 随机单个字母，区分大小写
     *
     * @return
     */
    private static String getRandomLetter() {
        return String.valueOf(codes[random.nextInt(codes.length - 1)]);
    }

    /**
     * 随机单个数字的字符串
     *
     * @return
     */
    private static String getRandomNum() {
        return String.valueOf(nums[random.nextInt(nums.length - 1)]);
    }
}
